{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d6997a54",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Converting train-images-idx3-ubyte.gz to NumPy Array ...\n",
      "Done\n",
      "Converting train-labels-idx1-ubyte.gz to NumPy Array ...\n",
      "Done\n",
      "Converting t10k-images-idx3-ubyte.gz to NumPy Array ...\n",
      "Done\n",
      "Converting t10k-labels-idx1-ubyte.gz to NumPy Array ...\n",
      "Done\n",
      "Creating pickle file ...\n",
      "Done!\n",
      "(60000, 784)\n",
      "(60000,)\n",
      "(10000, 784)\n",
      "(10000,)\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import os\n",
    "\n",
    "sys.path.append(os.pardir) # 为了导入父目录中的文件而进行的设定\n",
    "from dataset.mnist import load_mnist\n",
    "\n",
    "# 第一次调用会花费几分钟 ……\n",
    "(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True,normalize=False)\n",
    "\n",
    "# 输出各个数据的形状\n",
    "print(x_train.shape) # (60000, 784)\n",
    "print(t_train.shape) # (60000,)\n",
    "print(x_test.shape) # (10000, 784)\n",
    "print(t_test.shape) # (10000,)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b4e6be4",
   "metadata": {},
   "source": [
    "# 对于load_mnist(normalize=True, flatten=True, one_hot_label=False)\n",
    "### 第 1 个参数normalize设置是否将输入图像正规化为0.0～1.0的值。如果将该参数设置为False，则输入图像的像素会保持原来的0～255。\n",
    "### 第2个参数flatten设置是否展开输入图像（变成一维数组）。如果将该参数设置为False，则输入图像为1 × 28 × 28的三维数组；若设置为True，则输入图像会保存为由784个元素构成的一维数组\n",
    "### 第3个参数one_hot_label设置是否将标签保存为one-hot表示（one-hot representation）。one-hot表示是仅正确解标签为1，其余皆为0的数组，就像[0,0,1,0,0,0,0,0,0,0]这样。当one_hot_label为False时，只是像7、2这样简单保存正确解标签\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "dc2dadd3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "(784,)\n",
      "(28, 28)\n"
     ]
    }
   ],
   "source": [
    "import sys, os\n",
    "sys.path.append(os.pardir)\n",
    "import numpy as np\n",
    "from dataset.mnist import load_mnist\n",
    "from PIL import Image\n",
    "def img_show(img):\n",
    "    pil_img = Image.fromarray(np.uint8(img)) # 把保存为NumPy数组的图像数据转换为PIL用的数据对象\n",
    "    pil_img.show()\n",
    "(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True,normalize=False)\n",
    "img = x_train[0]\n",
    "label = t_train[0]\n",
    "print(label)\n",
    "print(img.shape)\n",
    "img = img.reshape(28, 28) # 把图像的形状变成原来的尺寸，由于flatten=True变为一维，现改为28*28\n",
    "print(img.shape)\n",
    "img_show(img) # 调用软件（自选）显示图片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "927f8db1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_data():\n",
    "    (x_train, t_train), (x_test, t_test) = \\load_mnist(normalize=True, flatten=True, one_hot_label=False)\n",
    "    return x_test, t_test\n",
    "def init_network():\n",
    "    with open(\"sample_weight.pkl\", 'rb') as f:\n",
    "    network = pickle.load(f)\n",
    "    return network\n",
    "def predict(network, x):\n",
    "    W1, W2, W3 = network['W1'], network['W2'], network['W3']\n",
    "    b1, b2, b3 = network['b1'], network['b2'], network['b3']\n",
    "    a1 = np.dot(x, W1) + b1\n",
    "    z1 = sigmoid(a1)\n",
    "    a2 = np.dot(z1, W2) + b2\n",
    "    z2 = sigmoid(a2)\n",
    "    a3 = np.dot(z2, W3) + b3\n",
    "    y = softmax(a3)\n",
    "    return y\n",
    "\n",
    "x, t = get_data()\n",
    "network = init_network()\n",
    "accuracy_cnt = 0\n",
    "for i in range(len(x)):\n",
    "    y = predict(network, x[i])\n",
    "    p = np.argmax(y) # 获取概率最高的元素的索引\n",
    "    if p == t[i]:\n",
    "        accuracy_cnt += 1\n",
    "print(\"Accuracy:\" + str(float(accuracy_cnt) / len(x)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
